/**
 * Generic state of a Store
 */
// export type StateTree = Record<string | number | symbol, unknown>;

import { reactive } from 'vue';

/**
 * 状态管理
 */
export class Store<T> {
  storeId: string;
  protected _state: T;
  /** getState */
  public get state() {
    return this._state;
  }
  /**
   * @param value
   */
  // public set state(value: T) {
  //   // if (value) {
  //   //   localStorage.setItem(this.id, JSON.stringify(value));
  //   // }
  //   this._state = value;
  // }
  /**
   * 构造函数
   * @param id  store ID
   * @param state s
   */
  constructor(id: string) {
    this.storeId = id;
    let str = sessionStorage.getItem(id);
    this._state = (!str ? {} : JSON.parse(str)) as T;
  }
  update(state: T) {
    this._state = state;
    this.saveChanges();
  }
  /**
   * 保存变化
   */
  saveChanges() {
    sessionStorage.setItem(this.storeId, JSON.stringify(this._state));
  }
  /** 清除状态 */
  clean() {
    this._state = {} as T;
    this.saveChanges();
  }
}
// export class Store {
//   /**
//    *
//    */
//   constructor(key: string) {
//     this.storeId = key;
//   }
//   storeId = '';
//   update<T extends Store>(obj: T) {
//     Object.assign(this, obj);
//   }
//   clear() {
//     localStorage.removeItem(this.storeId);
//   }
// }
export function useStore<T>(key: string): T {
  let store = new Store(key);
  let str = localStorage.getItem(key);
  if (!!str) return JSON.parse(str) as Readonly<T>;
  return undefined as any as Readonly<T>;
}
